package com.yeziji.dataCenter.config.mybatis;

import com.mybatisflex.core.audit.AuditManager;
import com.yeziji.common.Platform;
import com.yeziji.common.context.OnlineContext;
import com.yeziji.dataCenter.config.security.IgnoreUrls;
import com.yeziji.utils.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Optional;
import java.util.Set;

/**
 * mybatis-flex 配置
 *
 * @author hwy
 * @since 2024/10/26 19:08
 **/
@Configuration
public class MybatisFlexConfig {
    @Resource
    private IgnoreUrls ignoreUrls;
    private static final Logger logger = LoggerFactory.getLogger("mybatis-sql");

    public MybatisFlexConfig() {
        // 启动日志
        AuditManager.setAuditEnable(true);
        AuditManager.setMessageCollector(auditMessage -> {
            Set<String> sqlLogs = ignoreUrls.getSqlLogs();
            final String path = OnlineContext.getPath();
            if (path == null) {
                return;
            }
            for (String sqlLog : sqlLogs) {
                if (!ServletUtils.urlContains(sqlLog, path)) {
                    return;
                }
            }
            logger.info("[{}: {}-{}] {}, 执行时间: {}s", Optional.ofNullable(OnlineContext.getPlatform()).map(Platform::getPlatformName).orElse("None"), OnlineContext.getMdc(), auditMessage.getDsName(), auditMessage.getFullSql(), BigDecimal.valueOf(auditMessage.getElapsedTime()).divide(BigDecimal.valueOf(1000), 6, RoundingMode.HALF_UP));
        });
    }
}
